<!DOCTYPE html>
<html>
<head>
    <title>WebSocket</title>
    <meta charset="utf-8">
    <script src="jquery.js"></script>
</head>
<body>
<div>
    聊天
    <form>
        发送：<input type="text" class="woid" value="6">(我的ID)<br><br>
        接收：<input type="text" class="dfid" value="5">(接收者ID)<br><br>
        消息：<textarea class="msgnr"></textarea><br><br>
        <button class="tj" onclick="sendMessage()">提交</button> | <button class="tj" onclick="closeWebSocket()">断开</button>
    </form>
</div>
<div>
    回复消息
    <span class="hfmsgxx"></span>
</div>
</body>
<body>
<script type="text/javascript">

    // 假设有一个WebSocket连接对象
    let ws;
    let token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOiIxIiwidXNlcm5hbWUiOiJKc2xvZyIsIm1vYmlsZSI6IjEzNjA5MTY1NzQ2IiwiZXhwIjoxNzE3MDQxMDc4LCJuYmYiOjE3MTY5NTQ2Nzd9.CwzOxDpFwxV21UsuFK8wVhuxG5XAqNjTuDn4IZigJzw' //楼哥
    // 尝试建立WebSocket连接的函数
     function setupWebSocket() {
        // 使用示例
        let online = isSocketOpen()
        if (online == false) {
            try {
                ws = new WebSocket("ws://192.168.3.253:16968/ws/v1/chat/chat?token="+token);
                ws.onopen = function(event) {
                    console.log('WebSocket 连接已打开');
                };
                ws.onerror = function(error) {
                    console.error('WebSocket 出错:', error);
                };
                ws.onclose = function() {
                    console.log('WebSocket 连接已关闭');
                };
                ws.onmessage = function(event) {
                    showpage(event.data)
                    console.log('收到消息:', event.data);
                };
            } catch (error) {
                console.error('WebSocket 连接失败:', error);
            }
        } else {
            console.log('WebSocket:在线');
        }
    }

    // 函数用于检查当前是否断线
    function isSocketOpen() {

        console.log('-------------函数用于检查当前是否断线-----------------------------------------------------')
        if (!ws || ws.readyState == WebSocket.CLOSED) {
            console.log('断线')
            return false
        } else {
            console.log('在线')
            return true
        }
    }
     
    // 发送消息的函数，确保连接已建立
    function sendMessage() {

        var fid = $('.woid').val();
        var friend_id = $('.dfid').val()
        var msgnr = $('.msgnr').val()

        var senData = '{"from_id":'+fid+',"to_id":'+friend_id+',"content":"'+msgnr+'","token":"'+token+'"}'
        console.log(fid+"--------------"+friend_id)
        
        if (ws && ws.readyState === WebSocket.OPEN) {
            ws.send(senData);
        } else {
            console.error('WebSocket 连接不可用');
        }
    }

    //收到信息在页面
    function showpage(e){
        $('.hfmsgxx').text("回复消息:\n"+e);
    }
     
    // 关闭WebSocket连接的函数
    function closeWebSocket() {
        if (ws) {
            ws.close();
        }
    }
     
    // 初始化WebSocket连接
    setupWebSocket();
</script>
</body>
</html>